﻿//-----------------------------------------------------------------------
// <copyright file="RollingOverMinuteFileAppender.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: RollingOverMinuteFileAppender.cs
// * history : created by qinchaoyue 2017-12-18 09:42:44
// </copyright>
//-----------------------------------------------------------------------

using System;

namespace Slwy.Logger.Implements.Log4Net
{
    using log4net.Appender;

    /// <summary>
    /// 日志文件生成规则执行器
    /// </summary>
    public class RollingOverMinuteFileAppender : RollingFileAppender
    {
        /// <summary>
        /// 间隔分钟数
        /// </summary>
        private readonly int _nextMinute;

        /// <summary>
        /// 下一次生成日志文件时间
        /// </summary>
        private DateTime _nextMinuteEndDate;

        /// <summary>
        /// Initializes a new instance of the <see cref="RollingOverMinuteFileAppender"/> class.
        /// </summary>
        /// <param name="nextMinute">
        /// The next Minute.
        /// </param>
        public RollingOverMinuteFileAppender(int nextMinute)
        {
            this._nextMinute = nextMinute;
            this.CalcNextMinuteEnd(DateTime.Now);
        }

        /// <summary>
        /// 计算下一次生成日志文件时间
        /// </summary>
        /// <param name="time">时间</param>
        private void CalcNextMinuteEnd(DateTime time)
        {
            // Calc next sunday
            this._nextMinuteEndDate = time.AddMinutes(this._nextMinute);
        }

        /// <summary>
        /// The adjust file before append.
        /// </summary>
        protected override void AdjustFileBeforeAppend()
        {
            var now = DateTime.Now;

            if (now < this._nextMinuteEndDate)
            {
                return;
            }

            this.CalcNextMinuteEnd(now);
            //// As you included the day and month AdjustFileBeforeAppend takes care of creating 
            // new file with the new name
            base.AdjustFileBeforeAppend();
        }
    }
}
